const mongo = require('mongodb').MongoClient
const url = require('../config/config.js')

module.exports = {
    insert: function (collection,content) {  //增加
        mongo.connect(url.url, { useNewUrlParser: true }, (err, db) => {
            if (err) throw err;
            var dbs = db.db('cheliang');
            dbs.collection(collection).insertOne(content, err => {
                console.log(err);
            })
        })
    },
    find:function (collection,content,callback) {  //查询
        mongo.connect(url.url, { useNewUrlParser: true }, (err, db) => {
            if (err) throw err;
            var dbs = db.db('cheliang');
            dbs.collection(collection).find(content).sort({_id: -1}).toArray( (err,res) => {
                callback(res);
            })
        })
    },
    update:function(collection,old,now,callback){//更新数据
        mongo.connect(url.url, { useNewUrlParser: true }, (err, db) => {
            if (err) throw err;
            var dbs = db.db('cheliang');
            dbs.collection(collection).updateOne(old,now,(err,res)=>{
                if (err) throw err;
                callback();
            })
        })
    },
    count:function(collection,callback){
        mongo.connect(url.url, { useNewUrlParser: true }, (err, db) => {
            if (err) throw err;
            var dbs = db.db('cheliang');
            dbs.collection(collection).find().count((err,res)=>{
               callback(res);
            })
        })
    },
    drop:function(collection,content,callback){
        mongo.connect(url.url, { useNewUrlParser: true }, (err, db) => {
            if (err) throw err;
            var dbs = db.db('cheliang');
            dbs.collection(collection).deleteOne(content,(err,res)=>{
                if (err) throw err;
                console.log(res);
                callback(res);
            })
        })
    },
    find_num:function (collection,content,num,skip,callback) {  //查询
        mongo.connect(url.url, { useNewUrlParser: true }, (err, db) => {
            if (err) throw err;
            var dbs = db.db('cheliang');
            dbs.collection(collection).find(content).limit(num).skip(skip).sort({_id: -1}).toArray( (err,res) => {
                callback(res);
            })
        })
    },
}